package com.bw.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.common.base.BaseFragment
import com.bw.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviFragment<T:ViewDataBinding>:BaseFragment<T>() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        updateUI()
        //注册 EventBus
        EventBus.getDefault().register(this)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event:CustomEvent){
        if(event!= null && event.target==this::class.java.simpleName){
            handEvent(event)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        //取消注册 EventBus
        EventBus.getDefault().unregister(this)
    }


    private fun initData() {
        lifecycleScope.launch {
            sendViewIntent()
        }
    }
    //子类可以选择性的重写该方法


    private fun updateUI(){
        //监听生命周期 协程作用域 具备生命周期感知
        lifecycleScope.launch {
            //指定在Activity 执行某一个生命周期时 启动这个协程
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUIState()
            }
        }
    }

    open suspend fun sendViewIntent(){}

    open suspend fun collectUIState(){
    }

    open fun handEvent(event: CustomEvent){
    }
}